package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.client.ListFeignClient;
import com.atguigu.gmall.list.model.SearchAttr;
import com.atguigu.gmall.list.model.SearchParam;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: atguigu
 * @create: 2023-08-06 15:34
 */
@Controller
public class ListHtmlController {


    @Autowired
    private ListFeignClient listFeignClient;


    /**
     * 搜索页面渲染
     *
     * @param searchParam
     * @param model
     * @return
     */
    @GetMapping("/list.html")
    public String listHtml(SearchParam searchParam, Model model) {
        //1.将前端提交搜索过滤条件作为参数，远程调用搜索服务检索数据
        Result<Map> result = listFeignClient.search(searchParam);
        //2.将检索到数据封装到Model对象中
        model.addAllAttributes(result.getData());
        //3.将前端需要选中各种数据进行回显的数据 - 直接拷贝
        //3.1 用户提交请求参数 ${searchParam}
        model.addAttribute("searchParam", searchParam);

        //3.2 用户回显地址栏中请求 包含搜索条件完整链接 ${urlParam}
        model.addAttribute("urlParam", this.makeUrlParam(searchParam));

        //3.3 回显用户已选中品牌面包屑 ${trademarkParam}  品牌： 华为
        model.addAttribute("trademarkParam", this.makeTrademarkParam(searchParam));


        //3.4 回显用户已选中平台属性 ${propsParamList}
        model.addAttribute("propsParamList", this.makePropsParamList(searchParam));

        //3.5 回显页面排序效果${orderMap}   type:排序方式 sort:升降序
        model.addAttribute("orderMap", this.makeOrderMap(searchParam));

        return "/list/index";
    }

    /**
     * 根据用户选择排序方式，回显页面排序默认选中效果
     *
     * @param searchParam
     * @return
     */
    private Map<String, String> makeOrderMap(SearchParam searchParam) {
        Map<String, String> orderMap = new HashMap<>();
        if (StringUtils.isNotBlank(searchParam.getOrder())) {
            String[] split = searchParam.getOrder().split(":");
            if (split != null && split.length > 0) {
                //按照综合（分值）进行排序
                orderMap.put("type", split[0]);
                orderMap.put("sort", "asc".equals(split[1]) ? "asc" : "desc");
            }
        } else {
            //增加一个默认排序-按照ES相关性打分进行排序
            orderMap.put("type", "3");
            orderMap.put("sort", "desc");
        }
        return orderMap;
    }

    /**
     * 根据用户勾选平台属性，回显用户选择平台属性面包屑（多个）
     *
     * @param searchParam
     * @return
     */
    private List<SearchAttr> makePropsParamList(SearchParam searchParam) {
        //1.获取用户提交平台属性数组
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0) {
            List<String> propsList = Arrays.asList(props);
            //2.遍历数组封装为SearchAttr集合
            List<SearchAttr> searchAttrList = propsList.stream().map(prop -> {
                // prop = 平台属性Id:平台属性值名称:平台属性名
                String[] split = prop.split(":");
                SearchAttr searchAttr = new SearchAttr();
                if (split != null && split.length == 3) {
                    searchAttr.setAttrId(Long.valueOf(split[0]));
                    searchAttr.setAttrValue(split[1]);
                    searchAttr.setAttrName(split[2]);
                }
                return searchAttr;
            }).collect(Collectors.toList());
            return searchAttrList;
        }
        return null;
    }


    /**
     * 根据用户选择品牌，回显到页面，展示勾选的品牌名称
     *
     * @param searchParam
     * @return
     */
    private String makeTrademarkParam(SearchParam searchParam) {
        if (StringUtils.isNotBlank(searchParam.getTrademark())) {
            String[] split = searchParam.getTrademark().split(":");
            if (split != null && split.length == 2) {
                return "品牌：" + split[1];
            }
        }
        return null;
    }

    /**
     * 根据用户提交过滤条件，拼接搜索页面包含各种条件完整请求地址
     *
     * @param searchParam
     * @return
     */
    private Object makeUrlParam(SearchParam searchParam) {
        //1.声明基础请求路径 /list.html?
        StringBuilder stringBuilder = new StringBuilder("/list.html?");
        //2.处理关键字查询
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            stringBuilder.append("&keyword=" + searchParam.getKeyword());
        }
        if (StringUtils.isNotBlank(searchParam.getTrademark())) {
            stringBuilder.append("&trademark=" + searchParam.getTrademark());
        }
        if (searchParam.getCategory1Id() != null) {
            stringBuilder.append("&category1Id=" + searchParam.getCategory1Id());
        }
        if (searchParam.getCategory2Id() != null) {
            stringBuilder.append("&category2Id=" + searchParam.getCategory2Id());
        }
        if (searchParam.getCategory3Id() != null) {
            stringBuilder.append("&category3Id=" + searchParam.getCategory3Id());
        }
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0) {
            for (String prop : props) {
                //平台属性Id:平台属性值名称:平台属性名
                stringBuilder.append("&props=" + prop);
            }
        }
        return stringBuilder.toString();
    }
}
